import React, { useState, useEffect, memo } from "react";
import { useNavigate } from "react-router-dom";
import { Badge, Ellipsis, Image, List } from "antd-mobile";
import { useHandleBeforeHome } from "@/router/routerBefore";
import store from "@/store";
import MsgWrapper from "./style";

const Msg = memo((props) => {
  useHandleBeforeHome();
  let navigate = useNavigate();

  let [chatMsg, setChatMsg] = useState(store.getState().chat.chatmsg);
  let [users, setUsers] = useState(store.getState().chat.users);
  let [chatList, setChatList] = useState([]);

  const userId = store.getState().user._id;
  let msgGroup = {};

  useEffect(() => {
    let unsubscribe = store.subscribe(() => {
      setChatMsg(store.getState().chat.chatmsg);
      setUsers(store.getState().chat.users);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    let chatMsgInfo = chatMsg;
    let group = {};
    chatMsgInfo &&
      chatMsgInfo.forEach((v) => {
        group[v.chatid] = group[v.chatid] || [];
        group[v.chatid].push(v);
      });
    msgGroup = group;
    const chatListInfo = Object.values(msgGroup);
    // 显示的列表，最新的在最上面
    chatListInfo.sort((a, b) => {
      const a_last = getLast(a).create_time;
      const b_last = getLast(b).create_time;
      return b_last - a_last;
    });
    setChatList(chatListInfo);
  }, [chatMsg]);

  function getLast(arr) {
    return arr[arr.length - 1];
  }
  function handleClick(id, user) {
    navigate(`/chat?id=${id}&user=${user}`);
  }
  return (
    <MsgWrapper>
      <List header="聊天列表">
        {chatList.map((v, i) => {
          // 对方的id
          const targetId = v[0].from === userId ? v[0].to : v[0].from;
          const unreadNum = v.filter((item) => {
            return !item.read && item.to === userId;
          }).length;
          const lastItem = getLast(v);
          if (!users[targetId]) {
            return null;
          }
          let avatar = "";
          try {
            avatar = require(`../../components/img/${users[targetId].avatar}.png`);
          } catch (error) {
            // 如果图片出错，使用默认的头像
            avatar = require(`../../components/img/default.png`);
          }
          let showContent = "";
          console.log(lastItem.content);
          if (lastItem.content.startsWith("file_")) {
            showContent = lastItem.content.slice(19);
          } else {
            showContent = lastItem.content;
          }
          return (
            <List.Item
              extra={<Badge content={unreadNum || ""}></Badge>}
              key={i}
              onClick={() => {
                handleClick(targetId, users[targetId].name);
              }}
              prefix={
                <Image
                  src={avatar}
                  style={{ borderRadius: 20 }}
                  fit="cover"
                  width={40}
                  height={40}
                />
              }
              description={<Ellipsis direction="end" content={showContent} />}
            >
              {users[targetId].name}
            </List.Item>
          );
        })}
      </List>
    </MsgWrapper>
  );
});

export default Msg;
